// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package service_impl

import (
	"fmt"
	"net/url"
	"strconv"

	"gitcode.com/openseaotter/so_server/storage"
	"github.com/gin-gonic/gin"
)

type ListTagResponse struct {
	Name string   `json:"name"`
	Tags []string `json:"tags"`
}

func ProcessListTag(c *gin.Context) {
	groupName := c.Param("group")
	imageName := c.Param("name")
	nStr := c.Query("n")
	lastStr := c.Query("last")
	offset := 0
	limit := 0
	var err error
	if nStr != "" {
		limit, err = strconv.Atoi(nStr)
		if err != nil {
			SendError(c, 400, ERROR_CODE_NAME_INVALID, err.Error())
			return
		}
	}
	if lastStr != "" {
		offset, err = strconv.Atoi(lastStr)
		if err != nil {
			SendError(c, 400, ERROR_CODE_NAME_INVALID, err.Error())
			return
		}
	}

	groupInfo, err := storage.ImageGroupDao.Get(c.Request.Context(), groupName)
	if err != nil {
		SendError(c, 403, ERROR_CODE_DENIED, "image group not exist")
		return
	}

	//检查用户是否可以pull
	secName := GetSecretUsername(c)
	allow := false
	for _, secretName := range groupInfo.PermInfo.PullSecretNameList {
		if secName == secretName {
			allow = true
			break
		}
	}
	if !allow {
		SendError(c, 403, ERROR_CODE_DENIED, "not allow pull")
		return
	}

	//列出reference
	refItemList, err := storage.ImageReferenceDao.List(c.Request.Context(), groupName, imageName, false)
	if err != nil {
		SendError(c, 400, ERROR_CODE_NAME_INVALID, err.Error())
		return
	}

	response := &ListTagResponse{
		Name: fmt.Sprintf("%s/%s", groupName, imageName),
		Tags: []string{},
	}
	hasMore := false
	l := len(refItemList)
	if offset < l {
		hasMore = true
		end := l
		if limit != 0 {
			end = offset + limit
		}
		if end > l {
			end = l
			hasMore = false
		}
		for _, refItem := range refItemList[offset:end] {
			response.Tags = append(response.Tags, refItem.Reference)
		}
	}
	if hasMore && len(response.Tags) > 0 {
		tagLen := len(response.Tags)
		link := fmt.Sprintf("/v2/%s/%s/tags/list?n=%d&last=%d; rel=\"next\"", url.QueryEscape(groupName), url.QueryEscape(imageName), tagLen, offset+limit)
		c.Header("Link", link)
	}
	c.JSON(200, response)
}
